package com.zwps.biz.domain.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zwps.biz.domain.service.PermissionApiService;
import com.zwps.biz.api.model.dto.permission.api.AddPermissionApiDTO;
import com.zwps.biz.api.model.dto.permission.api.SelectPagePermissionApiDTO;
import com.zwps.biz.api.model.dto.permission.api.UpdatePermissionApiDTO;
import com.zwps.biz.api.model.vo.permission.api.SelectPagePermissionApiVO;
import com.zwps.biz.api.model.vo.permission.api.SelectPermissionApiVO;
import com.zwps.biz.dal.db.dao.PermissionApiDAO;
import com.zwps.biz.dal.db.dao.RolePermissionApiDAO;
import com.zwps.biz.dal.db.object.PermissionApiDO;
import com.zwps.biz.dal.db.object.RolePermissionApiDO;
import com.zwps.common.api.model.vo.PageInfoVO;
import com.zwps.common.core.exception.UserActionException;
import com.zwps.common.core.service.CommonService;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@AllArgsConstructor
@Slf4j
@Service
public class PermissionApiServiceImpl implements PermissionApiService, CommonService {

    private PermissionApiDAO permissionDAO;

    private RolePermissionApiDAO rolePermissionApiDAO;
    
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addPermissionApi(AddPermissionApiDTO dto) {
        if(dto!=null){
            PermissionApiDO vo = new PermissionApiDO();
            BeanUtils.copyProperties(dto,vo);

            if (permissionDAO.insert(vo) < 1) {
                throw new UserActionException("新增接口权限失败");
            }
        }else{
            throw new UserActionException("新增接口权限参数不能为空");
        }
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteBatchPermissionApi(String ids) {
        if(StringUtils.isBlank(ids)){
            throw new UserActionException("删除参数不能为空");
        }
        List<String> idList = Arrays.asList(ids.split(","));
        int result = permissionDAO.deleteBatchIds(Arrays.asList(ids.split(",")));
        if (result != idList.size()) {
            long permissionApiNum = permissionDAO
                    .selectCount(Wrappers.lambdaQuery(PermissionApiDO.class).in(PermissionApiDO::getId, idList));
            if (permissionApiNum > 0) {
                log.error("Delete Page Permissions id[{}] fail, select item {}, delete success {}", ids, idList.size(),
                        result);
                throw new UserActionException("删除失败");
            }
        }
        rolePermissionApiDAO.delete(Wrappers.lambdaQuery(RolePermissionApiDO.class).in(RolePermissionApiDO::getPermissionApiId, idList));
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updatePermissionApi(String id, UpdatePermissionApiDTO dto) {
        PermissionApiDO permissionApiDO = permissionDAO.selectById(id);
        if (permissionApiDO == null) {
            throw new UserActionException("修改接口权限对象不存在");
        }

        LambdaUpdateWrapper<PermissionApiDO> update = Wrappers.lambdaUpdate(PermissionApiDO.class);

        update.set(change(dto.getName(), permissionApiDO.getName()), PermissionApiDO::getName, dto.getName());
        update.set(change(dto.getPath(), permissionApiDO.getPath()), PermissionApiDO::getPath, dto.getPath());
        update.set(change(dto.getAntPath(), permissionApiDO.getAntPath()), PermissionApiDO::getAntPath, dto.getAntPath());
        update.set(change(dto.getMethod(), permissionApiDO.getMethod()), PermissionApiDO::getMethod, dto.getMethod());
        update.set(change(dto.getStatus(), permissionApiDO.getStatus()), PermissionApiDO::getStatus, dto.getStatus());

        if (StrUtil.isNotEmpty(update.getSqlSet())) {
            update.eq(PermissionApiDO::getId, id);
            if (permissionDAO.update(null, update) < 1) {
                throw new UserActionException("修改接口权限信息失败");
            }
        }
    }

    @Override
    public PageInfoVO<SelectPagePermissionApiVO> selectPermissionApiPage(SelectPagePermissionApiDTO dto) {
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        LambdaQueryWrapper<PermissionApiDO> query = Wrappers.lambdaQuery(PermissionApiDO.class);
        query.like(StrUtil.isNotEmpty(dto.getName()), PermissionApiDO::getName, dto.getName());
        query.like(StrUtil.isNotEmpty(dto.getMethod()), PermissionApiDO::getMethod, dto.getMethod());
        query.like(StrUtil.isNotEmpty(dto.getPath()), PermissionApiDO::getPath, dto.getPath());
        query.eq(dto.getStatus() != null, PermissionApiDO::getStatus, dto.getStatus());
        query.orderByAsc(PermissionApiDO::getAntPath);
        List<PermissionApiDO> selectList = permissionDAO.selectList(query);
        ArrayList<SelectPagePermissionApiVO> voList = new ArrayList<>();
        try (Page<PermissionApiDO> page = (Page<PermissionApiDO>) selectList) {
            PageInfoVO<SelectPagePermissionApiVO> pageInfo = new PageInfoVO<>(page.getPageNum(), page.getPageSize(),
                    page.getPages(), page.getTotal(), voList);
            for (PermissionApiDO permissionApiDO : selectList) {
                SelectPagePermissionApiVO vo = new SelectPagePermissionApiVO();
                if (permissionApiDO != null) {
                    BeanUtils.copyProperties(permissionApiDO, vo);
                }
                voList.add(vo);
            }
            return pageInfo;
        }
    }
    
    @Override
    public List<SelectPermissionApiVO> findPermissionApiAll() {
        List<SelectPermissionApiVO> result = new ArrayList<>();
        List<PermissionApiDO> list = permissionDAO.selectList(null);
        if(list!=null && !list.isEmpty()){
            list.forEach(permissionApiDO -> {
                SelectPermissionApiVO vo = new SelectPermissionApiVO();
                BeanUtils.copyProperties(permissionApiDO,vo);
                result.add(vo);
            });
        }
        return result;
    }

    @Override
    public SelectPermissionApiVO selectPermissionApi(String id) {
        PermissionApiDO permissionApiDO = permissionDAO.selectById(id);
        SelectPermissionApiVO selectPermissionApiVO = new SelectPermissionApiVO();
        if(permissionApiDO!=null) {
            BeanUtils.copyProperties(permissionApiDO,selectPermissionApiVO);
        }
        return selectPermissionApiVO;
    }
}
